package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;

/**
 * 汕头网友社区 网站解析
 * @author Chase
 *
 */
public class StqqBbsAnalyse implements AnalyseNews {

	private static final String[] regex = {
		"http://www.stqq.com/board.aspx[?]boardid=[0-9]*",
		"http://www.stqq.com/topic.aspx[?]topicid=[0-9]*",
		//http://www.stqq.com/topic.aspx?topicid=183937
	};


	
	public boolean isDetailPage(String url) {
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta meta = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String url = urlMeta.getUrl();
		/*
		 * 网站源码
		 */
		String htmltxt = urlMeta.getHtml();

		if(!isDetailPage(url)){
		}


		String title = null;
		String content = null;
		String author = null;
		Long date = null;
		Document doc = Jsoup.parse(htmltxt);

		/*
		 * 标题
		 */
		title = doc.select("title").text();
		title = StringUtils.substringBefore(title, "[");

		/*
		 * 时间
		 */
		date = DateUtils.matchDate(doc.select("td.padding").text());

		if(StringUtils.isBlank(title) || date == null){
		}

		/*
		 * 内容
		 */
		String contentStr = null;
		content = doc.select("td  blockquote div").html();
		if(StringUtils.isBlank(content))
			content = doc.select("td.hidden").html();
		contentStr = StringUtils.substringBetween(content, "output = \"", "\";");
		Document docContent = Jsoup.parse(contentStr);
		content = docContent.text();
		content=StringUtils.replace(content, "\\r\\n ", "").replace("800)this.width=800\\\">", "");
//		System.err.println(content);
		/*
		 * 作者
		 */
		if( doc.select("span.male").size() > 0)
			author = doc.select("span.male").get(0).text();
		if(StringUtils.isBlank(author))
			author = doc.select(".rowd").get(0).text();
		/*
		 * 链接
		 */
		meta.setUrl(url);

		/*
		 * 来源
		 */
		meta.setTitle(title);
		meta.setContent(content);
		meta.setAuthor(author);
		meta.setDate(date);


		return meta;
	}

	

	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}


	
}
